/**
 * 
 */
package com.hson.demo.base.web;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

/**
 * 上传语音文件
 * @author zenghh
 * @date 2015-12-05 10:21:06
 */
public class VoiceUploadUtil {

	protected static final Logger log = LoggerFactory.getLogger(VoiceUploadUtil.class);

	// 上传公共路径
	public static final String UPLOAD_PATH = "upload_files";
	// 语音文件检查失败时，返回错误信息的key值
	public static final String ERROR_KEY = "error";
	// 成功上传语音文件后，返回的相对路径地址
	public static final String VOC_URL = "vocUrl";
	public static final String VOC_SIZE = "vocSize";

	public static final String NO_FILE = "上传文件不能为空";
	public static final String UNKNOWN = "未知错误";
	
	public static final String FILE_NAME = "fileName";
	
	// 上传的语音文件最大不超过5M，单位是以bytes
	public static long maxSize = 5 * 1024 * 1024;

	// 定义允许上传的文件扩展名
	public static HashMap<String, String> extMap = new HashMap<String, String>();
	static {
		extMap.put("voc", "mp3,wma,wav,amr");
	}

	private static final String DATE_PATTERN = "yyyyMMdd";
	private static final String TIME_PATTERN = "yyyyMMddHHmmss";

	public static SimpleDateFormat sdf = new SimpleDateFormat(DATE_PATTERN);
	public static SimpleDateFormat df = new SimpleDateFormat(TIME_PATTERN);
	
	/**
	 * 保存上传的文件
	 * 
	 * @param file
	 * @param savePath
	 * @param dirName
	 * @return
	 * @throws Exception
	 */
	public static Map<String, Object> saveImage(MultipartFile file, String savePath, String dirName) throws Exception{
		return doUpload(file, savePath, dirName);
	}
	
	/**
	 * 文件上传
	 * 
	 * @param file
	 * @param savePath
	 * @param dirName
	 * @return
	 * @throws Exception
	 */
	public static Map<String, Object> doUpload(MultipartFile file, String savePath, String dirName) throws Exception {

		if (file != null) {
			Map<String, Object> ret = new HashMap<String, Object>();

			String filePathName = file.getOriginalFilename();
			// 文件保存目录URL
			String photoUrl = "/" + UPLOAD_PATH + "/";

			File uploadDir = new File(savePath);
			if (!uploadDir.isDirectory()) {
				uploadDir.mkdir();
			}
			if (!uploadDir.canWrite()) {
				ret.put(ERROR_KEY, "上传文件没有写权限！");
				return ret;
			}
			
			if (dirName == null) {
				dirName = "voice";
			}

			// 创建文件夹

			if (StringUtils.isNotBlank(savePath) && !savePath.endsWith("/")) {
				savePath += "/";
			}
			savePath += dirName + "/";
			photoUrl += dirName + "/";
			File saveDirFile = new File(savePath);
			if (!saveDirFile.exists()) {
				saveDirFile.mkdirs();
			}

			String ymd = sdf.format(new Date());
			savePath += ymd + "/";
			photoUrl += ymd + "/";
			File dirFile = new File(savePath);
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}

			// 检查文件大小
			long fileSize = file.getSize();
			if (fileSize > maxSize) {
				ret.put(ERROR_KEY, "上传文件大小超过限制。最大值5M。");
				return ret;
			}

			// 检查扩展名
			String fileExt = filePathName.substring(
					filePathName.lastIndexOf(".") + 1).toLowerCase();

			if (!Arrays.<String> asList(extMap.get("voc").split(",")).contains(fileExt)) {
				ret.put(ERROR_KEY, "上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get("voc") + "格式。");
				return ret;
			}

			String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
			photoUrl += newFileName;

			File dest = new File(savePath, newFileName);
			file.transferTo(dest);
			
			log.info("The file [" + filePathName
					+ "] had been upload to path [" + dest.getAbsolutePath()
					+ "] successfully.");
			System.out.println("The file [" + filePathName
					+ "] had been upload to path [" + dest.getAbsolutePath()
					+ "] successfully.");
			
			ret.put(FILE_NAME, filePathName);
			ret.put(VOC_URL, fileSize);
			ret.put(VOC_URL, photoUrl);
			return ret;
		}
		return null;
	}
}
